<?php
/**
 * Created by PhpStorm.
 * User: lx
 * Date: 2019/12/27
 * Time: 11:27
 */

namespace data\service;


use app\platform\controller\FamilyCard;
use data\model\FamilyCardModel;
use data\model\FamilyCardOrderModel;
use data\model\FamilyCardStyleModel as Enter;
use data\api\FamilyCard as IAddress;
use data\model\FamilyCardStyleModel;
use data\model\FamilyCardRecordsModel;
use data\model\FamilyRecordsModel;
use data\model\MemberFamilyModel;
use data\model\NsMemberModel;
use data\model\NsMemberRechargeModel;
use data\model\UserModel;
use data\service\BaseService as BaseService;


class Family extends BaseService implements IAddress
{
    private $enter;

    /**
     * Family constructor.
     * @author dzl
     */
    function __construct()
    {
        parent::__construct();
        $this->enter = new Enter();
    }

    /**
     * @param $data
     * @return mixed|void
     * @author dzl
     */
    public function addFamily($data)
    {

        $data['created_at'] = time();
        $data['updated_at'] = time();
        $retval = $this->enter->save($data);

    }

    /**
     * @param $condition
     * @param int $page_size
     * @param int $page_index
     * @param string $order
     * @return array|mixed
     * @author dzl
     */
    public function getFamilyQuery($condition, $page_size, $page_index, $order)
    {
        $res = $this->enter->pageQuery($page_index, $page_size, $condition, $order, '*');
        return $res;
    }

    /**
     * @param $condition
     * @return array|false|\PDOStatement|string|\think\Model
     * @author dzl
     */
    public function findFamily($condition)
    {
        $info = $this->enter->getInfo($condition, '*');
        return $info;
    }

    /**
     * @param $data
     * @param $id
     * @author dzl
     */
    public function editFamily($data, $id)
    {
        $data['updated_at'] = time();
        $retval = $this->enter->save($data, ['id' => $id]);
    }

    /**
     * @param $condition
     * @param $page_size
     * @param $page_index
     * @param $order
     * @return array
     * @author dzl
     */
    public function getPersonalList($condition, $page_size, $page_index, $order)
    {
        $model = new MemberFamilyModel();

        $res = $model->alias('mf')
            ->join('family_card_style fc', 'mf.card_id = fc.id', 'right')
            ->where($condition)
            ->field('mf.residual_times,fc.background,fc.frequency,fc.name,fc.card_details,mf.card_id,mf.id,mf.is_exhaust')->order($order)->select();
        $count = count($res);
        $list['list'] = $res;
        $list['total_count'] = $count;
        return $list;
    }

    /**
     * @param $page_size
     * @param $page_index
     * @param $order
     * @return array
     * @author dzl
     */
    public function  getFamilyCardList($page_size, $page_index, $order, $condition)
    {
        $model = new FamilyCardStyleModel();
        $res = $model->pageQuery($page_index, $page_size, $condition, $order, '*');

        $new_data = [];
        $result = [];
        foreach ($res['data'] as $key => $val){
            if(!in_array($val['theme'],$new_data)){
                array_push($new_data,$val['theme']);
            }
        }
        foreach ($new_data as $k => $v){
            $i = 0;
            foreach ($res['data'] as $key => $val){
                if($v == $val['theme'] && $i ==0){
                    array_push($result,$val);
                    $i++;
                }
            }
        }
        return $result;
    }

    /**
     * 购买亲友卡 T
     *
     * @param $data
     * @param $pay_info
     * @return mixed
     * @author dzl
     */
    public function purchaseFamilyCard($data)
    {
        $model = new FamilyCardStyleModel();
        $member_family = new MemberFamilyModel();
        $family_card_records = new FamilyCardRecordsModel();
        $family_records = new FamilyRecordsModel();
        $family_card_order = new FamilyCardOrderModel();

        $conditionO = [
            'order_no' => $data['order_no'],
            'status' => 0,
            'pay_type'=>1
        ];
        $orderArr = $this->getOnceOrder($conditionO);
        if (empty($orderArr)) {
            $result['status'] = false;
            $result['message'] = '未找到订单！';
            return $result;
        }
        $condition = [
            'id' => $orderArr['card_id'],
            'is_status' => 1
        ];
        //先获取亲友卡信息
        $card = $this->findFamily($condition);

        //亲友卡没找到
        if (empty($card)) {
            $result['status'] = false;
            $result['message'] = '亲友卡未找到！';
            return $result;
        }
        $price = $orderArr['price'];
        $frequency = $card['frequency'];
        //获取之前是否购买过此类亲友卡
        $condition = [
            'card_id' => $orderArr['card_id'],
            'member_id' => $orderArr['member_id']
        ];
        $member_arr = $member_family->getInfo($condition);

        if (empty($member_arr)) {
            //添加个人亲友卡
            $saveData = [
                'card_id' => $orderArr['card_id'],
                'member_id' => $orderArr['member_id'],
                'residual_times' => $frequency,
                'is_exhaust' => 1,
                'updated_at' => time(),
                'created_at' => time(),
            ];
            $where = [];
        } else {
            //修改个人亲友卡信息
            $saveData['residual_times'] = $member_arr['residual_times'] + $frequency;
            if ($member_arr['is_exhaust'] == 0) {
                $saveData['is_exhaust'] = 1;
            }
            $saveData['updated_at'] = time();
            $updateData['residual_times'] = $frequency + 1;
            $where['id'] = $member_arr['id'];
        }

        $records = [
            'details' => '购买 "' . $card['name'] . '" 亲友卡一张',
            'order_id' => ['order_no'],
            'card_id' => $data['card_id'],
            'transaction' => "扣款:" . $price,
            'pay_type' => $orderArr['type'],
            'balance' => 0,
            'created_at' => time(),
        ];

        $records_family = [
            'details' => '购买 "' . $card['name'] . '" 亲友卡一张',
            'created_at' => time(),
            'card_id' => $data['card_id'],
            'type' => 2,
            'member_id' => $orderArr['member_id'],
        ];

        $order =[
            'updated_at'=>time(),
            'status'=>1
        ];

        $member_family->startTrans();
        try {
            $res = $family_card_order->save($order,$conditionO);
            if (!$res) {
                $member_family->rollback();
                $result['status'] = false;
                $result['message'] = '更新订单异常！';
                return $result;
            }
            $res = $family_records->save($records_family);
            if (!$res) {
                $member_family->rollback();
                $result['status'] = false;
                $result['message'] = '更新个人记录异常！';
                return $result;
            }
            $res = $family_card_records->save($records);
            if (!$res) {
                $member_family->rollback();
                $result['status'] = false;
                $result['message'] = '更新记录异常！';
                return $result;
            }
            $res = $member_family->save($saveData, $where);
            if (!$res) {
                $member_family->rollback();
                $result['status'] = false;
                $result['message'] = '更新个人异常！';
                return $result;
            }
            $member_family->commit();
            $result['status'] = true;
            $result['message'] = '购买成功！';
            return $result;
        } catch (\Exception $e) {
            $member_family->rollback();
            $result['status'] = false;
            $result['message'] = '更新异常！';
            return $result;
//            return $e->getMessage();
        }

    }


    /**
     * 获取亲友卡，创建订单
     *
     * @param $data
     * @param $pay_inf
     * @return mixed
     * @author dzl
     */
    public function getPayWxInfo($data, $pay_inf){
        $family_card_order = new FamilyCardOrderModel();

        $condition = [
            'id' => $data['card_id'],
            'is_status' => 1
        ];
        //先获取亲友卡信息
        $card = $this->findFamily($condition);

        //亲友卡没找到
        if (empty($card)) {
            $result['status'] = false;
            $result['message'] = '亲友卡未找到！';
            return $result;
        }

        $conditionO = [
            'card_id' => $card['id'],
            'status' => 0,
            'member_id'=>$data['id'],
            'pay_type'=>1
        ];
        $orderNo =  $this->generateOrderNo($data);
        $orderArr = $this->getOnceOrder($conditionO);
        //订单已存在
        if (!empty($orderArr)) {
            $saveData = [
                'order_no'=> $orderNo,
            ];
            $family_card_order->save($saveData,['id'=>$orderArr['id']]);

            $result['status'] = true;
            $result['order_no'] = $orderNo;
            return $result;
        }
        $str_card = json_encode($card);

        $saveData = [
            'card_id'=> $card['id'],
            'member_id'=> $data['id'],
            'price'=> $card['price'],
            'pay_type'=> 1,
            'order_no'=> $orderNo,
            'order_info'=> "购买亲友卡",
            'status'=> 0,
            'created_at'=>time()
        ];
        $family_card_order->startTrans();
        try {
            $resA = $family_card_order->save($saveData);

            if (!$resA) {
                $family_card_order->rollback();
                $result['status'] = false;
                $result['message'] = '更新记录异常！';
                return $result;
            } else {
                $family_card_order->commit();
                $result['status'] = true;
                $result['order_no'] = $orderNo;
                return $result;
            }

        } catch (\Exception $e) {
            $family_card_order->rollback();
            $result['status'] = false;
            $result['message'] = '异常！';
            return $result;
//            return $e->getMessage();
        }


    }

    /**
     * @param $condition
     * @return array|false|\PDOStatement|string|\think\Model
     * @author dzl
     */
    public function getOnceOrder($condition){
        $family_card_order = new FamilyCardOrderModel();
        $res =$family_card_order->getInfo($condition);
//        var_dump($family_card_order->getLastSql());die;
        return $res;
    }

    /**
     * 生成订单号
     *
     * @param $data
     * @return string
     * @author dzl
     */
    public function generateOrderNo($data){
        $osn = date('Ymd').$data['card_id'].$data['id'].substr(implode(NULL, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 8);
        return $osn;
    }


    /**
     * 获取会员
     *
     * @param $where
     * @return array
     * @author dzl
     */
    public function getMemberFamily($where)
    {
        $model = new Member();
        $arr = $model->getMemberFamilyList(1, 50, $where, 'reg_time desc');
        return $arr;
    }

    /**
     * 亲友卡记录
     *
     * @param $where
     * @return array
     * @author dzl
     */
    public function geFamilyRecords($where)
    {
        $model = new Member();
        $arr = $model->getFamilyRecords(1, 50, $where, 'fr.created_at desc');
        return $arr;
    }

    /**
     * 唤起分享
     *
     * @param $request
     * @return mixed
     * @author dzl
     */
    public function shareInfo($request)
    {
        $model = new FamilyCardModel();
        $memberModel = new MemberFamilyModel();
        $familyModel = new FamilyRecordsModel();
        //生成卡片
        $card_no = $this->generateCardNo($request);
        $saveArrC = [
            'card_password' => $card_no,
            'style_id' => $request['card_id'],
            'is_status' => 1,
            'member_id' => $request['id'],
            'created_at' => time()
        ];
        $conditionM['member_id'] = $request['id'];
        $conditionM['is_exhaust'] = 1;

        $memberInfo = $memberModel->getInfo($conditionM);
        $residual_times = $memberInfo['residual_times'] - 1;

        if ($residual_times == 0) {
            $saveArrM['is_exhaust'] = 0;
        }
        $saveArrM = [
            'updated_at' => time(),
            'residual_times' => $residual_times
        ];

        $saveArrF = [
            'created_at' => time(),
            'card_id' => $request['card_id'],
            'type' => 1,
            'details' => '赠送中',
            'balance' => $residual_times,
            'status' => 1,
            'member_id' => $request['id'],
        ];

        $model->startTrans();
        try {
            $resA = $model->save($saveArrC);
            $resB = $memberModel->save($saveArrM, $conditionM);

            $saveArrF['card_no'] = $resA;
            $resC = $familyModel->save($saveArrF);

            if (!$resA || !$resB || !$resC) {
                $model->rollback();
                $data['status'] = false;
                $data['message'] = '更新记录异常！';
                return $data;
            } else {
                $model->commit();
                $data['status'] = true;
                $data['message'] = '分享成功！';
                return $data;
            }

        } catch (\Exception $e) {
            $model->rollback();
            $data['status'] = false;
            $data['message'] = '异常！';
            return $data;
//            return $e->getMessage();
        }
    }

    /**
     * 生成卡密
     *
     * @param $request
     * @return string
     * @author dzl TODO
     */
    public function generateCardNo($request)
    {
        $card_id = $request['card_id'];
        $id = $request['id'];
        $time = time();
        $head = "Dy";
        return $head . $card_id . $id . $time;
    }

    /**
     * 处理过期邀请
     *
     * @param $request
     * @return bool
     * @author dzl
     */
    public function clearOverShare($request)
    {
        $oneDay = 60 * 60 * 24;

        $model = new FamilyCardModel();
        $memberModel = new MemberFamilyModel();
        $familyModel = new FamilyRecordsModel();
        //生成卡片
        $conditionM['member_id'] = $request['id'];

        $memberInfo = $memberModel->getInfo($conditionM);
        $conditionM['is_status'] = 1;
        $memberCardOver = $model->getQuery($conditionM, '*', '');
        $idData = [];
        foreach ($memberCardOver as $key => $val) {
            $diff = time() - $val['created_at'];
            if ($diff > $oneDay) {
                //待处理数据
                array_push($idData, $val['id']);
            }
        }
        $num = count($idData);
        if($num == 0){
            return false;
        }

        $residual_times = $memberInfo['residual_times'] + $num;

        $saveDataC = [
            'is_status' => -1
        ];

        $saveDataM = [
            'residual_times' => $residual_times,
            'updated_at' => time(),
        ];
        if ($memberInfo['is_exhaust'] == 0) {
            $saveDataM['is_exhaust'] = 1;
        }

        $saveDataR = [
            'status' => 2,
            'balance' => $residual_times,
            'details' => '分享超时！余额返回'
        ];
        $idStr = implode(',',$idData);
        $whereId['id'] = array('in',$idStr);
        $model->startTrans();
        try {
            $resA = $model->save($saveDataC, $whereId);
            $resB = $memberModel->save($saveDataM, ['member_id' => $request['id']]);
            $resC = $familyModel->save($saveDataR, ['card_no'=>$idStr]);
            if (!$resA || !$resB || !$resC) {
                $model->rollback();
                return false;
            } else {
                $model->commit();
                return true;
            }

        } catch (\Exception $e) {
            $model->rollback();
            return false;
//            return $e->getMessage();
        }

    }

    /**
     * 获取支付详情
     *
     * @param $theme
     * @return array|false|\PDOStatement|string|\think\Model
     * @author dzl
     */
    public function getPayInfo($theme){
        $cardModel = new FamilyCardStyleModel();
        return $cardModel->getQuery(['theme'=>$theme,'is_status' =>1],'*','');
    }

    /**
     * 处理过期购买亲友卡订单数据
     *
     * @param $id
     * @return bool
     * @author dzl
     */
    public function updateOverOrder($id){
        $time = 60 * 5;
        $family_card_order = new FamilyCardOrderModel();
        $fiveMin = time() - $time;
        $list = $family_card_order->getQuery(['member_id'=>$id,'status'=>0,'created_at' =>['<',$fiveMin]],'*','');
        if(empty($list)){
            //没有待处理数据
            return true;
        }
        $str = "";
        foreach ($list as $key => $value){
            $str .= $value['id'].',';
        }
        $str = trim($str,',');
        $saveArrF = [
            'status' => -1,
            'updated_at'=>time()
        ];
        $resC = $family_card_order->save($saveArrF,['id'=>['in',$str]]);
        return true;
    }

    /**
     * 处理分享成功
     *
     * @param $request
     * @return mixed
     * @author dzl
     */
    public function handleShare($request){
        $model = new FamilyCardModel();
        $memberModel = new NsMemberModel();
        $familyModel = new FamilyRecordsModel();
        $userModel = new UserModel();

        //生成卡片
        $conditionM['member_id'] = $request['id'];
        $conditionM['is_status'] = 1;
        $conditionM['style_id'] = $request['card_id'];
        $conditionM['card_password'] = $request['card_password'];

        $cardInfo = $model->getInfo($conditionM);
        if(empty($cardInfo)){
            $result['status'] = false;
            $result['message'] = '分享失效！';
            return $result;
        }

        $saveArrF = [
            'family_name'=>$request['nickname'],
            'type' =>2,
            'details'=>"完成赠送"
        ];
        $saveArrM = [
            'member_level'=>2,
            'is_share'=>1,
            'parent_id'=>$request['id'],
            'reg_time'=>time()
        ];
        $password = md5(123456);
        $saveArrU = [
            'user_password'=>$password,
            'is_member'=>1,
            'user_tel'=>$request['phone'],
        ];

        $model->startTrans();
        try {
            $resA = $model->save(['is_status'=>2],['id'=>$cardInfo['id']]);
            $resC = $familyModel->save($saveArrF,['card_no'=>$cardInfo['id']]);
            $resU = $userModel->save($saveArrU);
            $saveArrM['uid'] = $resU;
            $resM = $memberModel->save($saveArrM);

            if (!$resA  || !$resC  || !$resU) {
                $model->rollback();
                $data['status'] = false;
                $data['message'] = '更新记录异常！';
                return $data;
            } else {
                $model->commit();
                $data['status'] = true;
                $data['message'] = '分享成功！';
                return $data;
            }

        } catch (\Exception $e) {
            $model->rollback();
            $data['status'] = false;
            $data['message'] = '异常！';
            return $data;
//            return $e->getMessage();
        }

    }
}